package com.wanghlme.bookstore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wanghlme.bookstore.bean.Cart;
import com.wanghlme.bookstore.entity.Trade;
import com.wanghlme.bookstore.service.TradeService;
import com.wanghlme.bookstore.mapper.TradeMapper;
import com.wanghlme.bookstore.util.common.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 订单操作业务实现类
 *
 * @author WangHailong
 */
@Service
public class TradeServiceImpl extends ServiceImpl<TradeMapper, Trade>
        implements TradeService {

    @Autowired
    private TradeMapper tradeMapper;

    /**
     * 生成一个订单
     *
     * @param cart       购物车
     * @param userinfoId 用户 ID
     * @param addressId  地址 ID
     * @return 订单编号
     */
    @Override
    public String insertTrade(Cart cart, String userinfoId, String addressId) {
        if (cart == null) {
            return null;
        }
        if (StringUtil.isNullEmptyBlank(userinfoId)) {
            return null;
        }
        if (StringUtil.isNullEmptyBlank(addressId)) {
            return null;
        }
        Date nowDate = new Date();
        String nowDateStr = new SimpleDateFormat("yyyyMMddHHmmss").format(nowDate);
        Trade trade = new Trade();
        trade.setUserinfoId(userinfoId);
        trade.setAddressId(addressId);
        trade.setTradeNumber(userinfoId.substring(0, nowDateStr.length()) + "-" + nowDate + "-" + tradeMapper.countTodayTrades() + 1);
        trade.setPrice(cart.getPrice());
        trade.setOrderTime(nowDate);
        return save(trade) ? trade.getTradeId() : null;
    }

    /**
     * 查询该用户的所有订单
     *
     * @param userinfoId 用户 ID
     * @return 查询到的订单列表
     */
    @Override
    public List<Trade> listTradeByUserinfoId(String userinfoId) {
        if (StringUtil.isNullEmptyBlank(userinfoId)) {
            return null;
        }
        return list(new QueryWrapper<Trade>().eq("userinfo_id", userinfoId));
    }

    /**
     * 查询处于某订单状态的所有订单
     *
     * @param status 订单状态
     * @return 查询到的订单列表
     */
    @Override
    public List<Trade> listTradeByStatus(int status) {
        return list(new QueryWrapper<Trade>().eq("status", status));
    }

    /**
     * 更新订单发货状态
     *
     * @param tradeId 订单 ID
     * @param status  订单状态
     * @return 操作结果
     */
    @Override
    public boolean updateTradeStatus(String tradeId, int status) {
        return update(new UpdateWrapper<Trade>().eq("trade_id", tradeId).set("status", status));
    }

}




